package com.quxian.chambercommerce.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.quxian.chambercommerce.Model.Model;

public class LoginFilter implements Filter {

	private final String JSONERROR = "needlogin";
	
	public void destroy() {

		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,

	FilterChain chain) throws IOException, ServletException {

//		HttpServletResponse res = (HttpServletResponse) ActionContext
//				.getContext().get(
//
//				org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
//
//		res.setContentType("text/json;charset=utf-8");
//
//		res.setCharacterEncoding("UTF-8");

		// 把ServletRequest和ServletResponse转换成真正的类型

		HttpServletRequest req = (HttpServletRequest) request;

		HttpSession session = req.getSession();

		// 由于web.xml中设置Filter过滤全部请求，可以排除不需要过滤的url

		String requestURI = req.getRequestURI();

		if (requestURI.endsWith("/weblogin/login.action")) {

			chain.doFilter(request, response);

			return;

		} else if (requestURI.endsWith("/login/login.action")) {

			chain.doFilter(request, response);

			return;

		}

		// 判断用户是否登录，进行页面的处理

		System.out.println("====session data===="+ session.getAttribute("user"));

		if (null == session.getAttribute("user")) {

			// 未登录用户，重定向到登录页面
			if("/sales/weblogin".indexOf(requestURI)!=-1){
				((HttpServletResponse) response).sendRedirect("/jsp/login.jsp");
			}else{
				responseOutWithJson((HttpServletResponse)response, createErrorJson("请登录后再使用"));
			}

			return;

		} else {

			// 已登录用户，允许访问

			chain.doFilter(request, response);

		}

	}

	/**
	 * 
	 * 以JSON格式输出
	 * 
	 * @param response
	 */

	protected void responseOutWithJson(HttpServletResponse response,

		JSONObject responseJSONObject) {

		// 将实体对象转换为JSON Object转换

		response.setCharacterEncoding("UTF-8");

		response.setContentType("application/json; charset=utf-8");

		PrintWriter out = null;

		try {

			out = response.getWriter();

			out.append(responseJSONObject.toString());

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			if (out != null) {

				out.close();

			}

		}

	}

	// 获取Filter初始化参数

	public void init(FilterConfig arg0) throws ServletException {

		// TODO Auto-generated method stub

		System.out.println("======filter init=====");

	}
	
	public JSONObject createErrorJson(String errorMsg) {
		
		Model json = new Model();
		json.setStatus(JSONERROR);
		json.setErrorMessage(errorMsg);
		json.setData(errorMsg);

		JSONObject jsonObject = JSONObject.fromObject(json); 
		System.out.println("=======jsonObject======"+jsonObject);
        
		return jsonObject;
	}
	

}
